package com.crt.nexus.security.component;

import com.crt.nexus.core.constant.SecurityConstants;
import com.crt.nexus.security.authentication.UserDetail;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

import java.util.LinkedHashMap;
import java.util.Map;

public class ResourceServerAuthenticationConverter extends DefaultUserAuthenticationConverter {

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<>(super.convertUserAuthentication(authentication));
        if (authentication.getPrincipal() instanceof UserDetail) {
            UserDetail user = (UserDetail) authentication.getPrincipal();
            response.put(SecurityConstants.DETAILS_USERNAME, user.getUsername());
        }
        return response;
    }

    /**
     * 解析JWT，把对应的属性放入资源服务器的Authentication
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(SecurityConstants.DETAILS_USERNAME) && map.get(SecurityConstants.DETAILS_USERNAME) != null) {
            Authentication auth = super.extractAuthentication(map);
            UserDetail detail = new UserDetail();
            detail.setUsername((String) map.get(SecurityConstants.DETAILS_USERNAME));
            detail.setPassword((String) auth.getCredentials());
            detail.setAuthorities(auth.getAuthorities());
            return new UsernamePasswordAuthenticationToken(detail, auth.getCredentials(), auth.getAuthorities());
        } else {
            return null;
        }
    }

}
